import { makeAutoObservable } from 'mobx'
import { Toast } from 'antd-mobile'
import * as Storage from '@/storage'
import { history } from 'umi'
import { getData, postData } from '@/servers/http'
import { api } from '@/servers/api'

export default class UserStore {
    public userData: Record<string, unknown> = {}
    hasToken = false
    constructor() {
        makeAutoObservable(this)
    }

    /**
     * 更新用户信息
     */
    update_user = (data: Record<string, unknown>) => {
        this.userData = data
    }

    /**
     * 退出登录
     */
    login_out = () => {
        Storage.delLocalStorage('USER_DATA')
        Storage.delCookie('TOKEN')
        this.userData = {}
        Toast.show({
            icon: 'success',
            content: '退出成功',
        })
        history.push('/user/login')
    }

    loginQuick = (params: any) => {
        postData(api.loginQuick, params).then(res => {
            this.update_user(res.data)
            this.hasToken = true
            Storage.setCookie('TOKEN', res.data.access_token)
            Storage.setLocalStorage('USER_DATA', res.data)
            Storage.setLocalStorage('GUIDE', '1')
            this.getUserInfo()
        })
    }
    /** 讲师免登 */
    teacherLoginQuick = (params: any) => {
        postData(api.teacherLoginQuick, params).then(res => {
            if (res.status === 200) {
                this.update_user(res.data)
                this.hasToken = true
                Storage.setCookie('TOKEN', res.data.access_token)
                Storage.setLocalStorage('USER_DATA', res.data)
                this.getUserInfo()
            }
        })
    }
    /** 游客免登 */
    visitorLoginQuick = (params: any) => {
        postData(api.visitorLoginQuick, params).then(res => {
            this.update_user(res.data)
            this.hasToken = true
            Storage.setCookie('TOKEN', res.data.access_token)
            Storage.setLocalStorage('USER_DATA', res.data)
            this.getUserInfo()
        })
    }

    /** 获取用户信息 */
    getUserInfo = async () => {
        await getData(api.usersLoginUserInfo).then(res => {
            this.userData = { ...this.userData, ...res.data }
            Storage.setLocalStorage('USER_DATA', this.userData)
        })
    }

    changeHasToken = (value: boolean) => {
        this.hasToken = value
    }
}
